package chapter14.robot;

import chapter14.nullperson.Null;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Collections;
import java.util.List;

/**
 * @author : DuJiabao
 * @Date : 2021/2/26 15:04
 * @Project : thinking_in_java
 * @File : null.java
 * @Desc :
 */
class NullRobotProxyHandler implements InvocationHandler {
  private String nullName;
  private Robot proxied = new NRobot();  // 一个空的Robot

  /**
   * 压根没创建传进来的Class对象的对象，只是拿了个SimpleName而已
   * @param type
   */
  public NullRobotProxyHandler(Class<? extends Robot> type) {
    nullName = type.getSimpleName() + "NullRobot";
  }

  private class NRobot implements Null, Robot {

    @Override
    public String name() {
      return nullName;
    }

    @Override
    public String model() {
      return nullName;
    }

    @Override
    public List<Operation> operations() {
      return Collections.emptyList();
    }
  }

  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    return method.invoke(proxied, args);
  }
}


public class NullRobot {
  public static Robot newNullRobot(Class<? extends Robot> type) {
    return (Robot) Proxy.newProxyInstance(NullRobot.class.getClassLoader(), new Class[]{Robot.class, Null.class}, new NullRobotProxyHandler(type));
  }

  public static void main(String[] args) {
    Robot[] bots = {new SnowRemovalRobot("SnowBee"), newNullRobot(SnowRemovalRobot.class)};
    for (Robot bot : bots) {
      Robot.Test.test(bot);
    }
  }
}
